<template>
  <div v-loading="loading">
    <el-button type="primary" @click="handlleAddStudent">添加学生</el-button>
    <el-button type="primary" @click="getMyStudents">刷新</el-button>
    <!--main-->
    <el-table :data="students" style="width: 100%; margin-top: 10px;" stripe :border="true">
      <el-table-column prop="uid" label="用户号" width="auto"></el-table-column>
      <!-- <el-table-column prop="teacher_id" label="指导教师ID" width="auto"></el-table-column>
      <el-table-column prop="teacher" label="指导教师" width="auto"></el-table-column> -->
      <el-table-column prop="name" label="姓名" width="auto"></el-table-column>
      <el-table-column prop="gender" label="性别" width="auto"></el-table-column>
      <el-table-column prop="birthdate" label="出生日期" width="auto"></el-table-column>
      <el-table-column prop="stage" label="阶段" width="auto"></el-table-column>
      <el-table-column prop="school" label="学院" width="auto"></el-table-column>
      <el-table-column prop="major" label="专业" width="auto"></el-table-column>
      <el-table-column prop="enrollment_date" label="入学日期" width="auto"></el-table-column>
      <el-table-column label="操作" width="auto">
        <template #default="scope">
          <el-button type="primary" @click="showStudentDetailInfo(scope.row)">详细信息</el-button>
          <!-- <el-button type="dangesr" @clic、k="handleDelete(scope.row)">禁用</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    
  </div>

  
  <!--添加学生-->
  <el-dialog v-model="dialogAddstudentVisible" title="添加学生">
    <el-form ref="formRef" :model="addStudentInfo" label-width="120px" :rules="rolesAddstudent" @submit.prevent="addStudent" hide-required-asterisk>
      <el-form-item label="账号" prop="p_username">
        <el-input v-model="addStudentInfo.p_username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="p_password">
        <el-input v-model="addStudentInfo.p_password"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="p_name">
        <el-input v-model="addStudentInfo.p_name"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="p_gender">
        <el-select v-model="addStudentInfo.p_gender">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期" prop="p_birthdate">
        <el-date-picker v-model="addStudentInfo.p_birthdate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>
      <el-form-item label="入学日期" prop="p_enrollment_date">
        <el-date-picker v-model="addStudentInfo.p_enrollment_date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>
      <el-form-item label="学院" prop="p_school_id">
        <el-select v-model="addStudentInfo.p_school_id" @change="onSchoolChange">
          <el-option
            v-for="(school, index) in schoolOptions"
            :key="index"
            :value="school.school_id"
            :label="school.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="专业" prop="p_major_id">
        <el-select v-model="addStudentInfo.p_major_id">
          <el-option
            v-for="(major, index) in filteredMajorOptions"
            :key="index"
            :value="major.major_id"
            :label="major.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学生阶段" prop="p_student_stage_id">
        <el-select v-model="addStudentInfo.p_student_stage_id">
          <el-option label="本科生" value="1"></el-option>
          <el-option label="研究生" value="2"></el-option>
          <el-option label="博士生" value="3"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogAddstudentVisible = false">取消</el-button>
        <el-button type="primary" @click="addStudent" native-type="submit">提交</el-button>
      </span>
    </template>
  </el-dialog>

  <!--学生详细信息-->
  <el-drawer v-model="drawerStudentDetail" title="详细信息" :with-header="true">
    <el-form label-width="60px"> 
        <el-form-item label="电话">{{ currentStudent.phone }}</el-form-item>
        <el-form-item label="邮箱">{{ currentStudent.email }}</el-form-item>
        <el-form-item label="地址">{{ currentStudent.address }}</el-form-item>
    </el-form>
  </el-drawer>

  
</template>

<script setup>
import http from '@/utils/axios.js'
import { reactive, ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'


const loading = ref(true)


// 从后端get初始化数据
const students = reactive([]);
onMounted(() => {
  try {
  // 获取我的学生列表
    getMyStudents()
  // 获取添加学生的选项
  
    http.get('/api/school')
    .then(res => {
      
      Object.assign(schoolOptions, res.data);
      // console.log(schoolOptions);
    })
    http.get('/api/major')
    .then(res => {
      Object.assign(majorOptions, res.data);
      // console.log(majorOptions);
    })
    
  } catch (error) {
    console.error('Error fetching student home info:', error);
  }
  
})

const getMyStudents = () => {
  // 获取自己学生数据
  http.get('/api/student/my_students')
    .then(res => {
      console.log(res);
      Object.assign(students, res.data);
      loading.value = false
    })
}

// 基本操作
//添加学生
// 添加学生的表单设置
const addStudentInfo = reactive({ });
const dialogAddstudentVisible = ref(false)
const handlleAddStudent = () => {
  dialogAddstudentVisible.value = true
  
}

const formRef = ref(null)
const rolesAddstudent = ref({
  p_username: [{ required: true, message: '请输入账号', trigger: ['submit', 'blur'] }],
  p_password: [{ required: true, message: '请输入密码', trigger: ['submit', 'blur'] }],
  p_name: [{ required: true, message: '请输入姓名', trigger: ['submit', 'blur'] }],
  p_gender: [{ required: true, message: '请选择性别', trigger: ['submit', 'change'] }],
  p_birthdate: [{ required: true, message: '请选择出生日期', trigger: ['submit', 'change'] }],
  p_enrollment_date: [{ required: true, message: '请选择入学日期', trigger: ['submit', 'change'] }],
  p_school_id: [{ required: true, message: '请选择学院', trigger: ['submit', 'change'] }],
  p_major_id: [{ required: true, message: '请选择专业', trigger: ['submit', 'change'] }],
  p_student_stage_id: [{ required: true, message: '请选择学生阶段', trigger: ['submit', 'change'] }]
})

const schoolOptions = reactive([]);  // 添加学生表单options设置
const majorOptions = reactive([]);
const filteredMajorOptions = computed(() => {
  return majorOptions.filter((item) => item.school_id === addStudentInfo.p_school_id);
});
const onSchoolChange = () => {
  if (addStudentInfo.p_major_id === void 0) {
    return
  }
  addStudentInfo.p_major_id = ''
  console.log(addStudentInfo.p_major_id);
}


const addStudent = async () => {

  formRef.value.validate(async (valid) => {
    if (valid) {
      // 表单验证通过,可以进行提交操作
      console.log(addStudentInfo);
      await http.post('/api/add_student', addStudentInfo)
      .then(res => {
        res = res.data
        if (res.code === 3000) {
          ElMessage.success('注册成功');
          dialogAddstudentVisible.value = false;
          getMyStudents()
        } else if (res.code===3001) {
          ElMessage.error('注册失败：'+res.data.error_msg)
          
        }
        console.log(res.data);
        
      })
      .catch(error => {
        console.error('Error fetching student home info:', error);
        // 在这里添加错误处理逻辑,例如显示错误消息给用户
      });
      console.log('Form submitted successfully')
    } else {
      // 表单验证失败,可以进行错误提示
      console.log('Form validation failed')
    }})
}


// 学生详细信息
const currentStudent = ref({})
const drawerStudentDetail = ref(false)
const showStudentDetailInfo = (student) => {
  currentStudent.value = { ...student };
  drawerStudentDetail.value = true
}


</script>